package com.learning.grpc.client;

import com.learning.grpc.service.LearningServiceGrpc;
import com.learning.grpc.service.RequestService;
import com.learning.grpc.service.ResponseService;
import com.learning.grpc.service.ServiceInfo;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class LearningClientImpl {

    private final ManagedChannel channel;

    private final LearningServiceGrpc.LearningServiceBlockingStub serviceBlockingStub;

    public LearningClientImpl(String host,int port) {
        this.channel = ManagedChannelBuilder.forAddress(host,port).usePlaintext().build();
        this.serviceBlockingStub = LearningServiceGrpc.newBlockingStub(channel);
    }

    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    private ResponseService saveService() {
        ServiceInfo serviceInfo = ServiceInfo.newBuilder().setIp("172.168.1.1").setPort("8080").build();
        ResponseService responseService = serviceBlockingStub.saveService(serviceInfo);
        return responseService;
    }

    public ResponseService getService() {
        RequestService requestService = RequestService.newBuilder().setClientId("12").putClientData("name","zhangbo").build();
        ResponseService service = serviceBlockingStub.getService(requestService);
        return service;
    }

    public static void main(String[] args) throws InterruptedException {
        LearningClientImpl client = new LearningClientImpl("localhost",8080);
        ResponseService responseService = client.saveService();
        log.info("clientCount:{}", responseService.getClientCount());

        ResponseService service = client.getService();
        log.info("clinetCount:{},serviceId:{}",service.getClientCount(),service.getServiceId());

        client.shutdown();

    }
}